package org.huangrui.juc.day04.locks;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 定制唤醒
 * @Author hr
 * @Create 2024-03-31 05:59
 */
public class T03_CustomWakeUp {
    public static void main(String[] args) {
        WakeUp up = new WakeUp();
        new Thread(() ->{
            for (int i = 1; i <= 10; i++) {
               up.print5(i);
            }
        },"AA").start();

        new Thread(() ->{
            for (int i = 1; i <= 10; i++) {
                up.print10(i);
            }
        },"BB").start();

        new Thread(() ->{
            for (int i = 1; i <= 10; i++) {
                up.print15(i);
            }
        },"CC").start();
    }
}
//第一步 创建资源类
class WakeUp{
    //定义标志位
    private byte flag = 1; // 1 AA     2 BB     3 CC
    private Lock lock = new ReentrantLock();
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();
    //打印5次，参数第几轮
    public void print5(int loop){
        lock.lock();
        try {
            while (flag != 1){
                c1.await();
            }
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName()+" :: "+i+" ：轮数："+loop);
            }
            flag = 2; //修改标志位 2
            c2.signal(); //通知BB线程
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void print10(int loop){
        lock.lock();
        try {
            while (flag != 2){
                c2.await();
            }
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName()+" :: "+i+" ：轮数："+loop);
            }
            flag = 3; //修改标志位 2
            c3.signal(); //通知CC线程
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void print15(int loop){
        lock.lock();
        try {
            while (flag != 3){
                c3.await();
            }
            for (int i = 0; i < 15; i++) {
                System.out.println(Thread.currentThread().getName()+" :: "+i+" ：轮数："+loop);
            }
            flag = 1; //修改标志位 2
            c1.signal(); //通知AA线程
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}